<?php
class Jssdk{
    private $appId = 'wx75d7dc5f9c92e40f';//appId

    //获取签名Package(用于微信JS接口)
    public function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        // 注意URL一定要动态获取不能hardcode.
        @$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = 'jsapi_ticket='.$jsapiTicket.'&noncestr='.$nonceStr.'&timestamp='.$timestamp.'&url='.$url;
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    //获取Ticket
    private function getJsApiTicket() {
        $url = 'http://bid999.com/api/jsticket';
        $postdata = array('secret'=>'b724a0315e6e50ebc7664d241b89b9d4');
        $res = json_decode($this->httpPost($url,$postdata),true);
        return $res['data'];
    }
    
    //POST请求
    private function httpPost($url, $data = null){
        $curl = curl_init();//初始化一个CURL对象
        curl_setopt($curl, CURLOPT_URL, $url);//设置你所需要抓取的URL
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);//假设上面的0换成1的话，那么接下来的$data就需要echo一下。
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);//post提交
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//设置curl参数，要求结果是否输出到屏幕上，为true(1)的时候是不返回到网页中
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    //生成随机字符串
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
}